package xp2p.svc.file;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;

import xp2p.adv.jxta.FileAdv;
import xp2p.svc.RequestorBase;

import net.jxta.content.ContentID;
import net.jxta.content.ContentService;
import net.jxta.content.ContentTransfer;
import net.jxta.peergroup.PeerGroup;

public class FileDownloader extends RequestorBase<FileAdv> implements
		FoundHandler, TransferCompleteHandler
{
	private FileFinder finder;
	public String ftype = "file";
	
	public FileDownloader()
	{
		super();
		finder = new FileFinder(this);
		finder.ftype = ftype;
		setListener(finder);
	}

	private PeerGroup group;
	private HashMap<String, ContentTransfer> downloads = new HashMap<String, ContentTransfer>();
	private HashMap<String, File> destinations = new HashMap<String, File>();
	private HashMap<String, Boolean> completes = new HashMap<String, Boolean>();

	private Object syncRoot = new Object();

	public void addDownload(File destination, String name)
	{
		destinations.put(name, destination);
		completes.put(name, false);
		finder.AddFile(name);
	}

	@Override
	public void Handle(ContentID id, String name)
	{
		ContentService svc = getGroup().getContentService();
		synchronized (syncRoot)
		{
			if (!downloads.containsKey(name))
			{
				ContentTransfer transfer = svc.retrieveContent(id);
				transfer.addContentTransferListener(new TransferListener(name,
						this));
				downloads.put(name, transfer);
				transfer.startTransfer(destinations.get(name));
			}
		}
	}

	@Override
	public void complete(String name)
	{
		synchronized (syncRoot)
		{
			completes.put(name, true);
		}
		if (AllTransfersComplpete())
		{
			setExit(true);
		}
	}

	public boolean AllTransfersComplpete()
	{
		synchronized (syncRoot)
		{
			Collection<Boolean> vals = completes.values();
			for (Boolean b : vals)
			{
				if (!b)
				{
					return false;
				}
			}
			return true;
		}
	}

	public PeerGroup getGroup()
	{
		return group;
	}

	public void setGroup(PeerGroup group)
	{
		this.group = group;
	}	
	
	@Override
	protected void beat()	
	{
		super.beat();
	}

	@Override
	public String getFType()
	{
		return ftype;
	}
}
